import hashlib
import json
import jwt
from datetime import datetime, timedelta
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from .models import User,Book,Category
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
def is_none(c):
    return  c is None or str(c).strip()==''
def jiami(pwd):
# return hashlib.md5(pwd.encode()).hexdigest()
    return hashlib.md5(pwd.encode()).hexdigest()
#登录
@csrf_exempt
def login(request):
    if request.method=='POST':
        data=json.loads(request.body)
        username=data['username']
        password=data['password']

        if is_none(username) or is_none(password):
            return JsonResponse({'error':'缺少必填参数'},status=401)

        if User.objects.filter(username=username).exists()==False:
            return JsonResponse({"error":"用户名为空"},status=401)

        #获取
        yonghu=User.objects.get(username=username)

        if yonghu.password!=jiami(password):
            return JsonResponse({"error":'密码错误'},status=401)

        expiration_time = datetime.now() + timedelta(minutes=120)

        # payload={'id':yonghu.id,'name':yonghu.username,'exp':int(expiration_time.timestamp())}
        payload={'id':yonghu.id,'name':yonghu.username,'exp':int(expiration_time.timestamp())}

        secret='123456'

        token=jwt.encode(payload,secret)

        return JsonResponse({'message':'登录成功','token':token},status=200)

@csrf_exempt
def booksAction(request):
    # token=request.META.get('HTTP_TOKEN')
    # secret = '123456'
    # if not token:
    #     return JsonResponse({'error':'请先登录'})
    # try:
    #     jwt.decode(token,secret,algorithms=['HS256'])
    # except jwt.ExpiredSignatureError:
    #     return JsonResponse({'error':'过期'})
    # except jwt.InvalidTokenError:
    #     return JsonResponse({"error":'无效'})
    #精确 模糊 查询 展示列表
    if request.method=='GET':
        all_data=Book.objects.all()
        total=len(all_data)
        name=request.GET.get('name','')
        status=request.GET.get('status','')
        # price=request.GET.get('price','')
        page=request.GET.get('page',1)
        page_size=request.GET.get('size') or 10

        if name:
            all_data=all_data.filter(name__contains=name)
        if status:
            all_data=all_data.filter(status=status)
        a=Paginator(all_data,page_size)
        all_data=a.get_page(page)
        ls=[]
        for i in all_data:
            ls.append({
                'id':i.id,
                'name':i.name,
                'category_id':i.category_id,
                'status':i.status,
                'description':i.description,
                'created_at':i.created_at,
                'price':i.price,
                'grade':i.grade
            })

        return JsonResponse({'data':ls,'total':total})
    #创建
    elif request.method=='POST':
        data=json.loads(request.body)
        name=data['name']
        category_id=data['category_id']
        status = data['status']
        description = data['description']
        price = data['price']
        grade = data['grade']
        result=Book.objects.create(
            name=name,
            category_id=category_id,
            status=status,
            description=description,
            price=price,
            grade=grade

        )
        return JsonResponse({
            'msg':result.id
        })
@csrf_exempt
def booksOperator(request,id):
    if request.method=="GET":
        if Category.objects.filter(id=id).exists()==False:
            return JsonResponse({'error':"id不存在"})
        category=Category.objects.get(id=id)
        books=category.children1.all()
        list=[]
        for i in books:
            list.append({
                'id': i.id,
                'name': i.name,
                'category_id': i.category_id,
                'status': i.status,
                'description': i.description,
                'created_at': i.created_at,
                'price': i.price,
                'grade': i.grade
            })
        return JsonResponse({'data':list})
    elif request.method=='DELETE':
        if Book.objects.filter(id=id).exists() == False:
            return JsonResponse({'error': "id不存在"})

        Book.objects.get(id=id).delete()

        return JsonResponse({'msg': "删除成功"})
@csrf_exempt
def update(request,id):
    books=Book.objects.get(id=id)
    if request.method=='PUT':
        data=json.loads(request.body)
        books.name=data['name'],
        # books.category_id=data['category_id']
        # books.status=data['status']
        # books.description=data['description']
        # books.created_at=data['created_at']
        # books.price=data['price']
        # books.grade=data['grade']
        books.save()

        return JsonResponse({'message':"修改成功"},status=200)

